<template>
    <view class="page">
        <!--    <view class="content">-->
        <!--        <image class="logo" src="/static/pay.png"></image>-->
        <!--        <view class="text-area">-->
        <!--            <text class="title">{{ title }}</text>-->
        <!--        </view>-->
        <!--    </view>-->
        <uni-drawer ref="showLeft" :width="drawerWidth" @change="showLeftChange">
            <uni-card style="background: transparent;"
                      :is-shadow="false"
                      :is-full="true"
                      :border="false"
                      :title="this.user.userNickName"
                      :sub-title="this.user.email"
                      :thumbnail="this.user.userHeadImg">
                <text class="uni-body">{{this.user.userSlogan}}</text>
            </uni-card>
            <uni-list>
                <uni-list-item showArrow title="个人信息" :to="`../info/info`"/>
            </uni-list>
            <view class="options-carts">
                <uni-goods-nav :options="options" :button-group="null" @click="optionsClick" />
            </view>
        </uni-drawer>

        <uni-card v-for="(card, index) in cardContentList" :title=card.title :sub-title='`${card.target}个小目标`'
                  :extra='`${card.totalMoney}RMB`' :thumbnail=this.iconArr[card.type] @click="getChartsData(index)">
            <text class="content_text">{{ card.content.length > 0 ? card.content : '暂无消费'}}</text>
        </uni-card>
        <view v-if="chartData != null && chartData.series[0].data.length > 0" class="ucharts_box_cont">
            <qiun-data-charts
                type="pie"
                :opts="opts"
                :chartData="chartData"
            />
        </view>
        <view v-else>
            <uni-card style="text-align: center" :is-shadow="false">
                <text class="uni-body">
                    {{
                        this.dateType === 0 ? '今日' : this.dateType === 1 ? '本月' : this.dateType === 2 ? '季度' : '今年'
                    }}暂无消费
                </text>
            </uni-card>
        </view>
        <uni-popup ref="logoutDialog" type="dialog">
            <uni-popup-dialog type="warn" cancelText="否" confirmText="是" title="正在退出" content="是否要退出登录？" @confirm="dialogConfirm"></uni-popup-dialog>
        </uni-popup>
    </view>
</template>

<script>
import {getHomeCard, selectConRecordsStatistics} from "../../js/api/home";
import {logout} from "../../js/api/user";
import {loading, toast, hide} from "../../js/utils/showTip";
import {
    getTodayIcon,
    getMonthIcon,
    getSeasonsIcon,
    getTwelveAnimalsIcon
} from "../../js/utils/staticUtil"

import UniCard from "../../uni_modules/uni-card/components/uni-card/uni-card.vue";
import UniPopup from "../../uni_modules/uni-popup/components/uni-popup/uni-popup.vue";
import UniPopupMessage from "../../uni_modules/uni-popup/components/uni-popup-message/uni-popup-message.vue";
import QiunDataCharts from "../../uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue";
import uvDivider from "../../uni_modules/uv-divider/components/uv-divider/uv-divider";
import UniSection from "../../uni_modules/uni-section/components/uni-section/uni-section";
import UniDrawer from "../../uni_modules/uni-drawer/components/uni-drawer/uni-drawer.vue";
import UniIcons from "../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import UniList from "../../uni_modules/uni-list/components/uni-list/uni-list.vue";
import UniListItem from "../../uni_modules/uni-list/components/uni-list-item/uni-list-item.vue";
import UniPopupDialog from "../../uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue";
import UniGoodsNav from "../../uni_modules/uni-goods-nav/components/uni-goods-nav/uni-goods-nav.vue";

export default {
    components: {
        UniGoodsNav,
        UniPopupDialog,
        UniListItem,
        UniList, UniIcons, UniDrawer, UniSection, QiunDataCharts, UniPopup, UniCard, UniPopupMessage, uvDivider},
    data() {
        return {
            title: '消费记录',
            iconArr: [],
            dateType: 0,
            drawerWidth: '',
            user: {
                username: '',
                userPhone: '',
                email: '',
                userNickName: '',
                userHeadImg: '',
                userSlogan: '',
                userRegistrationTime: ''
            },
            showLeft: false,
            cardContentList: [
                {
                    title: '',
                    target: '',
                    totalMoney: '',
                    icon: '',
                    content: ''
                }
            ],
            cardContent: {
                title: '',
                target: '',
                totalMoney: '',
                icon: '',
                content: ''
            },
            chartData: null,
            options: [
                {
                    icon: 'undo',
                    text: '退出',
                    method: 'logout'
                }, {
                    icon: 'gear',
                    text: '设置'
                }
            ],
            opts: {
                title: {
                    name: '消费统计'
                },
                legend: {
                    lineHeight: 20
                },
                fontSize: 8,
                color: [],
                padding: [5, 5, -10, 5],// 画布填充边距，顺序为上右下左
                enableScroll: false,
                extra: {
                    pie: {
                        activeOpacity: 0.5, // 启用Tooltip点击时，突出部分的透明度
                        activeRadius: 5, // 启用Tooltip点击时，突出部分的宽度（最大值不得超过labelWidth）
                        offsetAngle: 0, // 起始角度偏移度数，顺时针方向，起点为3点钟位置为0度（比如要设置起点为12点钟位置，即逆时针偏移90度，传入-90即可）
                        // customRadius: 2, // 自定义半径（一般不需要传值，饼图会自动计算半径，自定义半径可能会导致显示图表显示不全）
                        labelWidth: 15, // 数据标签到饼图外圆连线的长度
                        border: true, // 是否绘制各类别中间的分割线
                        borderWidth: 1, // 分割线的宽度
                        borderColor: "#FFFFFF", // 分割线的颜色
                        // linearType: "custom", // 渐变类型，可选值："none"关闭渐变,"custom"开启渐变
                        // customColor: ["#FA7D8D", "#EB88E2"] // 自定义渐变颜色，数组类型对应series的数组长度以匹配不同series颜色的不同配色方案，例如["#FA7D8D", "#EB88E2"]
                    }
                }
            }
        }
    },
    onLoad() {
        this.iconArr[0] = getTodayIcon()
        this.iconArr[1] = getMonthIcon()
        this.iconArr[2] = getSeasonsIcon()
        this.iconArr[3] = getTwelveAnimalsIcon()
        this.user = uni.getStorageSync("user");
        uni.getSystemInfo({
            success: (res) => {
                const width = res.windowWidth
                this.drawerWidth = Math.floor(width * 0.7); // 屏幕宽度，单位为px
            }
        })
        this.getHomeCard()
    },
    onReady() {
        this.getChartsData(this.dateType);
    },
    onPullDownRefresh() {
        loading('获取中...', true)
        this.getHomeCard();
        this.getChartsData(this.dateType)
        uni.stopPullDownRefresh();
        hide()
    },
    onNavigationBarButtonTap(e) {
        if (e.index == 0) {
            // open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
            !this.showLeft ? this.$refs.showLeft.open() : this.$refs.showLeft.close()
        } else {
            uni.navigateTo({
                url: '/pages/add-records/add-records'
            })
        }
    },
    methods: {
        getHomeCard() {
            getHomeCard().then(response => {
                if (response.code === 200) {
                    this.cardContentList = response.data
                    toast('获取成功！', 'success', false, 500)
                }
            })
        },
        /**
         * 获取统计图数据
         * @param dateType 0、day 1、month 2、seasons 3、year
         */
        getChartsData(dateType) {
            if (dateType === this.dateType) {
                return;
            }

            selectConRecordsStatistics(dateType).then(response => {
                if (response.code === 200) {
                    this.opts.color = [];
                    let res = {series: [{data: []}]};
                    for (const chartsDatum of response.data) {
                        this.opts.color.push(chartsDatum.typeColour)
                        res.series[0].data.push(
                            {
                                "name": chartsDatum.conType,
                                "value": chartsDatum.conAmount,
                                "labelText": chartsDatum.labelText
                            }
                        )
                    }
                    this.chartData = JSON.parse(JSON.stringify(res));
                    toast('获取成功！', 'success', false, 550)
                }
            })
            this.dateType = dateType;
        },
        showLeftChange() {
            this.controlPullToRefresh()
            this.showLeft = !this.showLeft
        },
        controlPullToRefresh() {
            // 当打开左侧抽屉式禁用下拉刷新，关闭左侧抽屉式开启下拉刷新
            // #ifdef APP-PLUS
            const pages = getCurrentPages();
            const page = pages[pages.length - 1];
            const currentWebview = page.$getAppWebview();
            currentWebview.setStyle({
                pullToRefresh: {
                    support: this.showLeft,
                    style: plus.os.name === 'Android' ? 'circle' : 'default'
                }
            });
            // #endif
        },
        logout() {
            this.$refs.showLeft.close()
            this.$refs.logoutDialog.open()
        },
        dialogConfirm() {
            logout().then(response => {
                if (response.code === 200) {
                    uni.clearStorageSync()
                    uni.reLaunch({
                        url: '/pages/login/login'
                    })
                }
            }).catch(response => {

            })
        },
        optionsClick(e){
            console.log(e)
            this[e.content.method]()
        }
    }
}
</script>

<style>
.ucharts_box_cont {
    width: 100%;
    flex: 1;
}

.content_text {
    color: #b0b0b0;
    font-size: 0.7em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.popup-content {
    @include flex;
    align-items: center;
    justify-content: center;
    padding: 15px;
    height: 50px;
    background-color: #fff;
}

.popup-height {
    @include height;
    width: 200px;
}

.text {
    font-size: 12px;
    color: #333;
}

.mb-10 {
    margin-bottom: 10px;
    font-size: 200px;
}

.drawer-img {
    height: 30%;
}

.options-carts {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    position: fixed;
    left: 0;
    right: 0;
    /* #ifdef H5 */
    left: var(--window-left);
    right: var(--window-right);
    /* #endif */
    bottom: 0;
}

.page{
    height: 100%;
    overflow: hidden; /* 防止页面内容超出时可以滚动 */
}
</style>
